<template>
  <div class="upload-avatar">
    <el-card>
      <h2>更换头像</h2>
      <el-upload
        class="avatar-uploader"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="onUploadFile"
      >
        <img v-if="imgUrl" :src="imgUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
      <el-button class="up" @click="handleUpload">上传</el-button>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { uploadAvatar, saveAvatarUrl } from '@/api/avatar.js'

const imgUrl = ref('');
const selectedFile = ref(null);

const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw);
  selectedFile.value = uploadFile.raw;
};

const handleUpload = async () => {
  if (!selectedFile.value) {
    return
  }

  try {
    const response = await uploadAvatar(selectedFile.value);
    const imageUrl = response.data.url;
    await saveAvatarUrl(imageUrl);
    alert('头像上传成功');
  } catch (error) {
    console.error('上传失败', error);
    alert('上传失败，请重试');
  }
};
</script>

<style scoped>
.upload-avatar {
  padding: 140px;
  background-color: #f5f5f5;
}

.el-card {
  max-width: 500px;
  margin: 0 auto;
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
  width: 188px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  left:20px;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}
.up {
  width: 10%;
  height: 20%;
  font-size: 14px;
  position: relative;
  left: 35px;
}
</style>

